package servlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.ShoppingCartItem;

import controller.LoginController;

import dao.CustomerDBAO;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    		throws ServletException, IOException {
    	doPost(request, response);
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	String id = request.getParameter("id");
    	String password = request.getParameter("password");
    	boolean	result = false;

    	try {
			result = LoginController.authenticate(id, password);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	    if(result){
	    	HttpSession session = request.getSession(true);
	    	session.setAttribute("userId", id);
	    	ArrayList<ShoppingCartItem> list = new ArrayList<ShoppingCartItem>();
	    	session.setAttribute("cart", list);
	    	session.setAttribute("nbrOfItems", 0);
	    	session.setAttribute("total", 0);
	    	request.getRequestDispatcher("/store").forward(request,response);
	    }
	    else{
	    	request.setAttribute("error", "User name or password is incorrect!");
	    	request.getRequestDispatcher("index.jsp").forward(request,response);
	    }
	}

}
